package cn.itsource.pay.controller;

import cn.itsource.basic.contants.PayConstants;
import cn.itsource.order.domain.ProductOrder;
import cn.itsource.order.service.IProductOrderService;
import cn.itsource.pay.domain.PayBill;
import cn.itsource.pay.service.IPayBillService;
import cn.itsource.quartz.service.IQuartZService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class AliPayController {

    @Autowired
    private IQuartZService quartZService;
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IProductOrderService productOrderService;

    //同步通知
    @RequestMapping("/returnUrl")
    public String returnUrl(){

        return "redirect:http://127.0.0.1/success.html";
    }
    //异步通知
    @RequestMapping("/notifyUrl")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request){

        try {
            //确认订单的状态   --修改
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

           // boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            //商户订单号【我们系统生成的订单号】
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号【第三方交易单号】
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态【当前订单订单交易状态】
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if (trade_status.equals("TRADE_SUCCESS")){
                //1.根据 out_trade_no 查询我们自己的 PayBill
                PayBill payBill = payBillService.loadByOrderSn(out_trade_no);
                payBill.setUpdateTime(new Date());
                payBill.setState(1);
                payBill.setUnionPaySn(trade_no);
                payBillService.update(payBill);
                //2.根据 根据 业务类型 确定查找 订单【服务  商品 领养  宠物】
                if (PayConstants.BUSINESSTYPE_PRODUCT.equals(payBill.getBusinessType())){
                    ///3.修改订单状态
                    ProductOrder productOrder = productOrderService.queryById(payBill.getBusinessKey());
                    productOrder.setState(1);
                    productOrder.setPaySn(trade_no);
                    productOrderService.update(productOrder);
                }
                //取消定时任务
                quartZService.removeJob(out_trade_no);

                return  "success";
            }else {
                return "fail";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


}
